// 小数点后保留两位

export const towNumber = (val) => {
    if (val === '') {
    return 0
  } else {
    let handleNum = val+ ''
    if(handleNum.indexOf('.') !== -1){
      // 有小数点
      let index = handleNum.lastIndexOf(".");
      // 获得字符串前面的数据
      var subBefore = handleNum.substring(0,index);
      // 获得字符串后面的数据
      var subBack = handleNum.substring(index+1,handleNum.length);
      // 判断小数点后数据是否多于两位
      if(subBack.length>2){
        subBack = subBack.substring(0,2);
        handleNum  = subBefore+"."+subBack;
        return handleNum
      }
      else{
        handleNum  = subBefore+"."+subBack;
        return handleNum
      }
    } else {
      return handleNum
    }
  }
}
/** 数字超过一万转换为万
 * @param { Number } value 数值
 * @param { Number } decimal 保留几位小数
 * @returns { String }
 */
 export const transNumberToShort = (value, decimal = 2) => {
  const k = 10000
  const sizes = ['', '万', '亿', '万亿']
  let i = undefined
  let str = ''
  if(value < k) {
    str = value
  } else {
    i = Math.floor(Math.log(value) / Math.log(k))
    str = parseFloat(((value / Math.pow(k, i))).toFixed(decimal)) + sizes[i]
  }
  return str
}
/**
 * 将距离格式化
 * <1000m时 取整,没有小数点
 * >1000m时 单位取km,一位小数点
 */
 export const formatDistance = (num) => {
  if (num <1000) {
    return num.toFixed(0) + 'm';
  } else if (num > 1000) {
    return (num / 1000).toFixed(1) + 'km';
  }
}
/**
 * 将时间戳转换为时间日期（如：2021-07-12 10:20:35）
 */
export const dateFormat  = (timestamp, format) => {
  if (String(timestamp).length === 10) {
    timestamp = timestamp * 1000
  }
  let date = new Date(timestamp)
  let Y = date.getFullYear()
  let M = date.getMonth() + 1
  let D = date.getDate()
  let hour = date.getHours()
  let min = date.getMinutes()
  let sec = date.getSeconds()
  if (format === 'YYYY') {
    return Y // 2021
  } else if (format === 'YYYY-MM') { // 2021-07
    return Y + '-' + (M < 10 ? '0' + M : M)
  } else if (format === 'YYYY-MM-DD') { // 2021-07-12
    return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D)
  } else if (format === 'HH:mm:ss') { // 10:20:35
    return (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)
  } else if (format === 'YYYY-MM-DD HH:mm') { // 2021-07-12 10:20
    return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min)
  } else if (format === 'YYYY-MM-DD HH:mm:ss') { // 2021-07-12 10:20:35
    return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)
  } else {
    return '--'
  }
}
/**
 * 手机号码中间加*
 */
export const mobileHide = (tel) => {
  tel = "" + tel
  return tel.replace(tel.substring(3,7), "****")

}

export const roundTo = (num, scale) => {
  //计算10的指数，例如保留两位就是100
  let p = Math.pow(10, scale);
  //先乘以指数，然后四舍五入取整，再除以指数
  return Math.round(num * p) / p
}

// 输入框 输入金额 保留2位小数
export const limitNumberInput = () => {
  // return ("" + val).replace(/[^\d^\.]+/g, "").replace(/^0+(\d)/, "$1").replace(/^\./, "0.").match(/^\d*(\.?\d{0,2})/g)[0] || "";
}
// 获取随机字母
export function randomCoding(num, type) {
  var result = [];
  let typeObj = {
      number: () => {
          for (var i = 0; i < num; i++) {
              var randNum = Math.ceil(Math.random() * 10);
              result.push(randNum)
          }
      },
      letter: () => {
          for (var i = 0; i < num; i++) {
              var ranNum = Math.ceil(Math.random() * 25);
              result.push(String.fromCharCode(65 + ranNum));
          }
      },
      numLetter: () => {
          for (var i = 0; i < num.num; i++) {
              var numItem = Math.ceil(Math.random() * 10);
              result.push(numItem);
          }
          for (var j = 0; j < num.letter; j++) {
              var ranNum = Math.ceil(Math.random() * 25);
              result.push(String.fromCharCode(65 + ranNum));
          }
      }
  }
  typeObj[type]()
  return result.join('');
}
// 千分位分隔 11,234.22 || 12,345 || 23%
export function toThousands(num) {
  num = num.toString()
  if(num == null) {return null}
  const reg=/(?=(?!(\b))(\d{3})+$)/g;
  const hasPercent = num.indexOf('%')
  if(hasPercent > -1) {
    num = num.substring(0,hasPercent)
  }
  const arr = num.split('.')
  if(arr.length == 1) {
    num=arr[0].replace(reg,",")
  }else {
    num=arr[0].replace(reg,",") + '.' + arr[1];
  }

  if(hasPercent > -1) {
    num = num + '%'
  }

  return num;
}


export default {
  towNumber,
  transNumberToShort,
  formatDistance,
  dateFormat,
  mobileHide,
  limitNumberInput,
}
